#include "Common.h"

#include "iconv.h"

namespace FUNCTION {
    std::string GBK2UTF8(const std::string& str)
    {
        iconv_t cd = iconv_open("UTF-8", "GBK");
        if (cd == (iconv_t)-1)
        {
            return "";
        }

        size_t ilen = str.size();
        size_t olen = ilen * 3 / 2;

        std::string output;
        output.resize(olen);

        std::string& input = const_cast<std::string&>(str);

        char* in = &input[0];
        char** pin = &in;

        char* out = &output[0];
        char** pout = &out;

        if (iconv(cd, pin, &ilen, pout, &olen)) return "";

        iconv_close(cd);

        return output;
    }

    std::string UTF82GBK(const std::string& str) {
        iconv_t cd = iconv_open("GBK", "UTF-8");
        if (cd == (iconv_t)-1)
        {
            return "";
        }

        size_t ilen = str.size();
        size_t olen = ilen * 2 / 3;

        std::string output;
        output.resize(olen);

        std::string& input = const_cast<std::string&>(str);

        char* in = &input[0];
        char** pin = &in;

        char* out = &output[0];
        char** pout = &out;

        if (iconv(cd, pin, &ilen, pout, &olen)) {
            iconv_close(cd);
            return "";
        }

        iconv_close(cd);

        return output;
    }
}
